package Concurent;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by root on 17-6-8.
 * 锁是解决线程安全问题,锁的新写法
 */

public class LockDemo2 {
    public static String name = "李雷";
    public static String gender = "男";

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();

        new Thread(new T17(lock)).start();
        new Thread(new T18(lock)).start();
    }

}

class T17 implements Runnable {
    private Lock lock = null;
    public T17(Lock lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        while(true){
            lock.lock();
        if ("李雷".equals(LockDemo1.name)) {
            LockDemo1.name = "韩梅梅";
            LockDemo1.gender = "女";
        } else {
            LockDemo1.name = "李雷";
            LockDemo1.gender = "男";
        }
        lock.unlock();
    }
}

}

class T18 implements Runnable {
    private Lock lock = null;
    public T18(Lock lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();

            System.out.println(LockDemo1.name + ":" + LockDemo1.gender);
            lock.unlock();
        }
    }

}